#!/bin/bash

#编译指令，source ./make.sh ${PR_URL}
#编译指令，source ./make.sh https://gitee.com/openharmony-sig/flutter_flutter/pulls/29

DIR=$PWD

# 在workspace中执行
function set_env() {
    export JAVA_HOME=$DIR/flutter_env/jdk-17.0.8

    export PUB_HOSTED_URL=https://pub.flutter-io.cn
    export FLUTTER_STORAGE_BASE_URL=https://flutter-ohos.obs.cn-south-1.myhuaweicloud.com

    export FLUTTER_HOME=$DIR/flutter_flutter
    export PATH=$JAVA_HOME/bin:$FLUTTER_HOME/bin:$PATH

    export TOOL_HOME=$DIR/flutter_env/command-line-tools-5.0.3.600
    export HOS_SDK_HOME=$DIR/new-os-sdk
    export DEVECO_SDK_HOME=$HOS_SDK_HOME
    export NODE_HOME=$DIR/flutter_env/node-v16.14.2-linux-x64
    export PATH=$TOOL_HOME/ohpm/bin:$TOOL_HOME/hvigor/bin:$NODE_HOME/bin:$PATH
}

set_env

WORK_ROOT=$PWD

function get_project_name() {
    # 默认构建项目路径
    DEFALUT_PROJECT='packages/pigeon/example/app'
    local diff_url=$1.diff
    local diff_name=${diff_url##*/}
    local retval=1
    if [ ! -f $diff_name ]
    then
        wget $diff_url
        if [ $? -ne 0 ]
        then
            echo "$DEFALUT_PROJECT"
            reutrn $retval
        fi
    fi
    local diff_str=`cat $diff_name | grep "diff --git"`
    # 匹配a/开头，/ohos/entry/.* 中间的路径，因为不同项目的目录结构不同
    local regex="a/(.*)/ohos/entry/.*"
    for diff in $diff_str
    do
    local tmp=`echo $diff | grep "/"`
    if [ ! -z "$tmp" ]
    local find=0
    then
        if [[ $tmp =~ $regex ]]; then
            tmp=${BASH_REMATCH[1]}
            echo "$tmp"
            retval=0
            find=1
            break
        fi
    fi
    done
    if [ "$find" -eq 0 ];then
        echo "$DEFALUT_PROJECT"
    fi
    return $retval
}

PROJECT=$(get_project_name $1)

#执行构建
echo "项目位置：$PROJECT"
echo "PATH============== $PATH"
echo "HOS_SDK_HOME============== $HOS_SDK_HOME"
echo "NODE: $(node --version), $(which node)"
ls -alh $TOOL_HOME/tool/node/bin/node
echo "OHPM: $(ohpm --version) $(which ohpm)"
ls -alh $TOOL_HOME/ohpm/bin/ohpm

if [ "$(grep 11 third_party/flutter/packages/$PROJECT/ohos/build-profile.json5)" != "" ]; then
    pre_script/sdk_setup.sh 11
else
    pre_script/sdk_setup.sh 12
fi

flutter doctor -v
cd ./third_party/flutter/packages/$PROJECT && flutter pub get && rm -rf ./pubspec.lock
flutter build hap --target-platform ohos-arm64 --debug
echo $DIR
mv ./ohos/entry/build/default/outputs/default/entry-default-unsigned.hap $DIR/hap_out